"""
Dice
A module to help with rolling dice. Includes a class to represent a particular
type of die roll, and common dice groups, e.g. 1d6, 3d6, 1d4, 2d10, 1d100
"""

import random

class Dice(object):
    numDice = 1
    numSides = 6
    rollMin = 1
    diceDict = {}
    
    def __new__(cls, value=(1,6), rollMin=1):
        """
        Can be called Dice("3d6") or Dice((3,6))
        """
        if isinstance(value, (str,unicode)):
            parts = value.split('d')
            numDice, numSides = map(int, parts)
            
        elif hasattr(value, '__getitem__'):
            numDice, numSides = value
        
        index = "%sd%s,%s" % (numDice, numSides, rollMin)
        
        if cls.diceDict.has_key(index):
            return cls.diceDict[index]
        else:
            self = super(Dice, cls).__new__(cls)
            self.numDice = numDice
            self.numSides = numSides
            self.rollMin = rollMin
            cls.diceDict[index] = self
            return self

    def roll(self):
        """
        Return a sequence for multiple die rolls, or
        the value of a single roll.
        """
        rv = [ random.randint(self.rollMin, self.numSides)
               for i in range(self.numDice) ]
        
        if len(rv) == 1:
            return rv[0]
        else:
            return rv

    def rollSum(self):
        """ Return the sum of a roll. """
        if self.numDice == 1:
            return self.roll()
        return sum(self.roll())



# Standard dice rolls
dice1d6     = Dice('1d6')
dice3d6     = Dice('3d6')
dice1d10    = Dice('1d9', 0)
dice2d10    = Dice('2d9', 0)
dice2d9     = Dice('2d9')
dice1d100   = Dice('1d100', 0)
dice1d4     = Dice('1d4')
dice1d20    = Dice('1d20')
dice1d12    = Dice('1d12')



if __name__ == "__main__":
    for d in range(100):
        print dice1d6.roll()